﻿using System.Text;

namespace CabinetGrid.DeviceDriver.IModules.Impls;

public class RFIDUHFReaderModule : IModule
{
    private readonly ILogger _logger;
    private readonly ViewModel _viewModel;

    public RFIDUHFReaderModule( ILoggerFactory loggerFactory, ViewModel viewModel )
    {
        _logger = loggerFactory.CreateLogger( nameof( RFIDUHFReaderModule ) );
        _viewModel = viewModel;
    }

    public async Task StartAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "uhf" ) return;

        try
        {
            _viewModel.AppConfig.RFIDReaderList.ForEach( config =>
            {
                if ( config.Enable is false ) return;

                var api = new Dev.Integration.UHFReader.ApiClientBuilder( )
                                                       .UseReaderKind( config.Kind )
                                                       .UseReaderConfig( o =>
                                                       {
                                                           o.MillisecondsTimeout = 5 * 1000;
                                                           o.Connect.ConnectArgs = config.ConnectArgs;
                                                           o.Connect.ConnectType = config.ConnectType;
                                                           o.MonitorLogAction = ( level, log ) =>
                                                           {
                                                               switch ( level )
                                                               {
#if DEBUG
                                                                   case Dev.Integration.HFReader.Constants.LogLevel.Debug:
                                                                       {
                                                                           ConsoleWirter.Debug( $"+ [uhf] {log}" );
                                                                           break;
                                                                       }
#endif
                                                                   case Dev.Integration.HFReader.Constants.LogLevel.Info:
                                                                       {
                                                                           _logger.Info( log );
                                                                           break;
                                                                       }
                                                                   case Dev.Integration.HFReader.Constants.LogLevel.Warn:
                                                                       {
                                                                           _logger.Warning( log );
                                                                           break;
                                                                       }
                                                                   case Dev.Integration.HFReader.Constants.LogLevel.Error:
                                                                       {
                                                                           _logger.Error( log );
                                                                           break;
                                                                       }
                                                               }
                                                           };
                                                       } )
                                                       .Build( );

                api.OnOpenedHandler = ( s, e ) => ConsoleWirter.Success( $"+ [uhf] OnOpenedHandler: {api.ReaderId}" );
                api.OnClosedHandler = ( s, e ) => ConsoleWirter.Warning( $"+ [uhf] OnClosedHandler: {api.ReaderId}" );
                api.OnInventoryStartHandler = ( s, e ) => ConsoleWirter.Info( $"+ [uhf] OnInventoryStartHandler" );
                api.OnInventoryStopHandler = ( s, e ) =>
                {
                    // WS: 上报盘点结果
                    _viewModel.WebSocketClientNoityWithRFIDUHFTagList( api.ReaderId );

                    var builder = new StringBuilder( );

                    var result = _viewModel.RFIDUHFTagList.Select( ( tag, index ) => $"标签 [{index + 1}] {tag.EPC}\t{tag.TID}\t{tag.ScanCount}\t{tag.AntList.Select( i => $"{i.AntNo}:{i.RSSI}:{i.Count}" ).ToStringWithComma( )}" )
                                                          .ToStringWithNewLine( );

                    builder.AppendLine( result );
                    builder.AppendLine( );

                    ConsoleWirter.Success( builder.ToString( ) );
                };
                api.OnInventoryTagHandler = ( s, e ) => _viewModel.AddOrUpdateRFIDUHFTag( e.Tag );

                _viewModel.RFIDUHFReaderList.Add( api );
            } );

            _logger.Info( $"注册成功" );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注册失败: {ex.Message}" );
        }

        await Task.CompletedTask;

        // 重连机制
        _ = Task.Factory.StartNew( ( ) =>
        {
            while ( true )
            {
                _viewModel.RFIDUHFReaderList.ForEach( api =>
                {
                    try
                    {
                        if ( api.ReaderState == Dev.Integration.UHFReader.Constants.ReaderState.Close )
                        {
                            api.Open( );
                        }
                    }
                    catch ( Exception ex )
                    {
                        ConsoleWirter.Warning( $"+ [uhf] {api.Config.Connect.ConnectArgs} 连接失败: {ex.Message}" );
                    }
                    finally
                    {
                        Thread.Sleep( 1000 );
                    }
                } );

                Thread.Sleep( 10 * 1000 );
            }
        } );
    }

    public async Task StopAsync( CancellationToken cancellationToken )
    {
        if ( _viewModel.AppConfig.RFIDReaderCategory != "uhf" ) return;

        try
        {
            _viewModel.RFIDUHFReaderList.ForEach( api =>
            {
                api.Close( );
            } );

            _logger.Info( $"注销成功" );
        }
        catch ( Exception ex )
        {
            _logger.Error( $"注销失败: {ex.Message}" );
        }

        await Task.CompletedTask;
    }
}
